package com.chentongwei.core.user.biz;

import com.chentongwei.cache.redis.IHashCache;
import com.chentongwei.common.constant.MsgEnum;
import com.chentongwei.common.constant.RedisEnum;
import com.chentongwei.common.constant.ResponseEnum;
import com.chentongwei.common.creator.ResultCreator;
import com.chentongwei.common.email.biz.MailBiz;
import com.chentongwei.common.email.constant.MailContentTypeEnum;
import com.chentongwei.common.entity.Result;
import com.chentongwei.common.exception.BussinessException;
import com.chentongwei.common.util.CommonExceptionUtil;
import com.chentongwei.common.util.DateUtil;
import com.chentongwei.core.user.dao.IUserDAO;
import com.chentongwei.facade.user.entity.io.LoginIO;
import com.chentongwei.facade.user.entity.io.RegistUserIO;
import com.chentongwei.facade.user.entity.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.Date;

/**
 * 用户业务接口实现类
 *
 * @author TongWei.Chen 2017-06-10 15:17
 **/
@Service
public class UserBiz {
    private static final Logger LOG = LoggerFactory.getLogger(UserBiz.class);

    @Autowired
    private IUserDAO userDAO;
    @Autowired
    private IHashCache hashCache;
    @Autowired
    private MailBiz mailBiz;

    /**
     * 注册
     *
     * @param userIO：用户信息
     * @return Result
     */
    @Transactional
    public Result regist(RegistUserIO userIO) {
        //email重复检查
        boolean emailFlag = userDAO.getByEmail(userIO.getEmail());
        CommonExceptionUtil.flagCheck(emailFlag, ResponseEnum.EMAIL_ALREADY_EXISITS);

        userDAO.regist(userIO);
        sendMail(userIO);
        //记录系统日志
        LOG.info("【{}】注册成功！", userIO.getId());
        return ResultCreator.getSuccess();
    }

    /**
     * 登录
     *
     * @param loginIO：登录信息
     * @return Result
     */
    public Result login(LoginIO loginIO) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        UserVO user = userDAO.login(loginIO);
        CommonExceptionUtil.nullCheck(user, ResponseEnum.EMAIL_OR_PWD_ERROR);
        CommonExceptionUtil.userDisabledCheck(user.getStatus());
        CommonExceptionUtil.userActiveCheck(user.getIsActive());
        //TODO 检查是否完善过资料
        //存到redis
        hashCache.cacheHash(RedisEnum.LOGINED_USER.getKey(), loginIO.getToken(), user);
        return ResultCreator.getSuccess(user);
    }

    /**
     * 检查电子邮件是否唯一
     *
     * @param email：电子邮件
     * @return Result
     */
    public Result getByEmail(String email) {
        boolean flag = userDAO.getByEmail(email);
        CommonExceptionUtil.flagCheck(flag, ResponseEnum.EMAIL_ALREADY_EXISITS);
        return ResultCreator.getSuccess();
    }

    /**
     * 激活用户
     *
     * @param userId：用户id
     * @return Result
     */
    @Transactional
    public Result activeUser(Integer userId) {
        UserVO userVO = userDAO.getById(userId);
        CommonExceptionUtil.nullCheck(userVO, ResponseEnum.USER_NOT_EXISTS);
        try {
            int hour = DateUtil.hourDiff(userVO.getCreateTime(), new Date());
            if(hour > 2) {
                throw new BussinessException(ResponseEnum.EMAIL_TIMEOUT_ERROR);
            }
        } catch (ParseException e) {
            LOG.info("【{}】激活失败！", userId);
            e.printStackTrace();
        }
        //检查是否已经激活过
        CommonExceptionUtil.alreadyActiveCheck(userVO.getIsActive());
        userDAO.activeUser(userId);
        LOG.info("【{}】激活成功！", userId);
        return ResultCreator.getSuccess();
    }

    /**
     * 删除没有激活的用户（目前在task任务里用的，每天跑一次小程序删除那些大于两小时还没激活的用户。）
     * @return Result
     */
    public Result deleteUnActiveUser() {
        userDAO.deleteUnActiveUser();
        return ResultCreator.getSuccess();
    }

    /**
     * 注册时发送邮件
     *
     * @param userIO：注册用户
     */
    private void sendMail(RegistUserIO userIO) {
        StringBuilder sb = new StringBuilder();
        sb.append(MsgEnum.EMAIL_CONTENT.getValue());
        sb.append(MsgEnum.EMAIL_CONTENT1.getValue());
        sb.append(MsgEnum.EMAIL_CONTENT2.getValue());
        sb.append(userIO.getId());
        sb.append(MsgEnum.EMAIL_CONTENT3.getValue());
        sb.append(MsgEnum.EMAIL_CONTENT4.getValue());

        try {
            mailBiz
                    .title(MsgEnum.EMAIL_TITLE.getValue())
                    .content(sb.toString())
                    .contentType(MailContentTypeEnum.HTML)
                    .to(userIO.getEmail())
                    .send(null);
        } catch (Exception e) {
            LOG.error("【{}】发送邮件失败！", userIO.getId());
            e.printStackTrace();
        }
    }

}